// 初始化地图
const map = L.map('heatmap-container').setView([39.9042, 116.4074], 13);

// 配置热力图
const cfg = {
  radius: 25,
  maxOpacity: 0.8,
  scaleRadius: true,
  useLocalExtrema: true,
  latField: 'lat',
  lngField: 'lng',
  valueField: 'count'
};

const heatmapLayer = new HeatmapOverlay(cfg);
map.addLayer(heatmapLayer);

// 动态加载数据
function updateHeatmap(bounds, zoom) {
  fetch(`/api/heatmap?neLat=${bounds.getNorth()}&neLng=${bounds.getEast()}
                &swLat=${bounds.getSouth()}&swLng=${bounds.getWest()}
                &zoom=${zoom}`)
    .then(res => res.json())
    .then(data => {
      const points = data.points.map(p => ({
        lat: p.centerLat,
        lng: p.centerLng,
        count: p.value
      }));
      heatmapLayer.setData({ data: points });
    });
}

// 地图移动事件监听
map.on('moveend', debounce(() => {
  const bounds = map.getBounds();
  updateHeatmap(bounds, map.getZoom());
}, 500));